﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VsxFactory.Modeling.VisualStudio;
using VsxFactory.Modeling.VisualStudio.Synchronization;

namespace VsxFactory.Modeling.Strategies.Rules
{
    public class TypeGenerationRule : NodeGenerationRule
    {
        private string _typeNameFormatString;

        public TypeGenerationRule() : this(null)
        {
        }

        public TypeGenerationRule(Type melType=null, string outputFileNameFormat = "{Name}.cs", string typeNameFormatString = null) 
            : base(melType, outputFileNameFormat)
        {
            if (typeNameFormatString == null)
                _typeNameFormatString = System.IO.Path.GetFileNameWithoutExtension(outputFileNameFormat);
            else
                _typeNameFormatString = typeNameFormatString;
        }

        protected override void Rename(IVsProject project, GenerationSpec wrapper, string oldName)
        {
            ExpressionEvaluator oldNameEvaluator = new ExpressionEvaluator(wrapper.ModelElement, oldName);
            ExpressionEvaluator newNameEvaluator = new ExpressionEvaluator(wrapper.ModelElement);

            string newName = newNameEvaluator.Evaluate(_typeNameFormatString);
            string ns = wrapper.FullName.Substring(0, wrapper.FullName.Length - newName.Length);
            string oldFullName = ns + oldNameEvaluator.Evaluate(_typeNameFormatString);
            CodeRefactoringHelper.Rename(wrapper.ModelElement.Store, oldFullName, newName);

            base.Rename(project, wrapper, oldName);
        }
    }
}
